<?php
namespace Admin\Controller;
use Admin\Api\MenuApi;
use Admin\Api\CallbackApi;
use Think\Controller;
class WechatController extends Controller {
	public function inAction(){
    	$callbackApi = new CallbackApi();
    	$menuApi=new MenuApi();
    	if (!isset($_GET["echostr"])) {
    	    //响应事件
    	    $menuApi->creatMenu();
    	    $result=$this->responseMsg();
    	    echo $result;
    	}else {
    	    //验证token
	    	$echoStr = $_GET["echostr"];
	        if($callbackApi->checkSignature()){
	        	echo $echoStr;exit;
	        }
    	}
    }
    /**
     * 菜单创建
     */
 	public function menuAction(){
    	$menuApi = new MenuApi();
		$creatMenu = $menuApi->creatMenu();//创建菜单
    	if($creatMenu['errcode'] == 0){
    		echo '修改成功';
    	}
    }
    /**
     * 响应消息
     */
    public function responseMsg(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 
        if (!empty($postStr)){
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $ERENT_TYPE = trim($postObj->MsgType);
            switch ($ERENT_TYPE){
                //事件
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                    //文本
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                    //图片
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                    //位置
                case "location":
                    $result = $this->transmitText($object, "这是一个位置信息");
                    break;
                    //录音
                case "voice":
                    $result = $this->transmitText($object, "这是一个录音信息");
                    break;
                    //视频
                case "video":
                    $result = $this->transmitText($object, "这是一个视频信息");
                    break;
                case "link":
                    $result = $this->transmitText($object, "这是一个链接信息");
                    break;
                default:
                    $result = "unknown msg type: ".$ERENT_TYPE;
                    break;
            }
            echo $result;
            }else {
                echo "欢迎关注易卡商户";
                exit;
            }  
      }
    /**
     * 接收事件消息
     */
    public function receiveEvent($object){
        $content = "";
        $responseType="text";
        switch ($object->Event)
        {
            case "subscribe":
                $responseType="subscribe";
               $object->Content="subscribe";
               $openid=$object->FromUserName;
                break;
            case "unsubscribe":
                $openid = $object->FromUserName;
                break;
            case "SCAN":
                $content = "扫描场景 ".$object->EventKey;
                break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    case "COMPANY":
                        $content = "易卡会员卡网络科技有限公司提供互联网相关产品与服务。";
                        break;
                    default:
                        $openid= $object->FromUserName;
                        $responseType="other";
                        $object->Content=$object->EventKey;
                        break;
                }
                break;
            case "LOCATION":
                $content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                return $result;
                break;
            case "VIEW":
                $openid=strval($object->FromUserName);
                $content = "跳转链接 ".$object->EventKey;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        //发送文本消息
        if($responseType=="text"){
            $result = $this->transmitText($object, $content);
            return $result;
        //触发文本回复
        }else{
            $result=$this->receiveText($object);
            return $result;
        }
    }
     /**
      * 文本文字触发事件
      * @param   $object
      * @return  
      */
     public  function receiveText($object){
             //触发关注回复
             $title="为什么要用易卡系统？打开了解我们";
             $desc="了解易卡，了解一款帮你赚钱的收银系统";
             $link="http://mp.weixin.qq.com/s?__biz=MzIwOTM3Mjk4Nw==&mid=100000060&idx=1&sn=933396b0dbdf64cc2f19f51b0366f85c&scene=0&previewkey=B%2FR4rwNMvCyHLa61rUF8pswqSljwj2bfCUaCyDofEow%3D#wechat_redirect";
             $picurl="https://mmbiz.qlogo.cn/mmbiz/EBDJbGICTUr4nCYXF6ibgsbmM2PCs18jaymYNq7chozvTwjuN3XIwHYoWlTYN6Rt7QIg1Unm8pgxZUickezbRHbg/0?wx_fmt=jpeg";
             $newsArray=array(
                 'Title'=>$title,
                 'Description'=>$desc,
                 'PicUrl'=>$picurl,
                 'Url'=>"http:www.baidu.com"
             );
             $result=$this->transmitImageInfo($object,$newsArray);
            echo $result;
    }
    /**
     * 图片消息触发事件
     */
     public  function receiveImage($object){
        $imageArray['MediaId']=trim($object->MediaId);
        $mediaid=strval($object->MediaId);
        $result = $this->transmitImage($object, $imageArray);
        return $result;
    }
    /**
     * 发送文本消息
     * @param   $object
     * @param   $content
     * @return  
     */
    public  function transmitText($object, $content){
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }
    
    /**
     * 回复图片消息
     */
    public function transmitImage($object, $imageArray){
        $itemTpl = "<Image>
                        <MediaId><![CDATA[%s]]></MediaId>
                    </Image>";
        $item_str = sprintf($itemTpl, $imageArray['MediaId']);
        $textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[image]]></MsgType>
        $item_str
        </xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }
    /**
     * 发送图文消息
     * @param unknown $object
     * @param unknown $newsArray
     * @return string|unknown
     */
    public function transmitImageInfo($object,$newsArray){
          if(!is_array($newsArray)){
              return "";
          }
        $itemTpl = " <item>
                            <Title><![CDATA[%s]]></Title>
                            <Description><![CDATA[%s]]></Description>
                            <PicUrl><![CDATA[%s]]></PicUrl>
                            <Url><![CDATA[%s]]></Url>
                      </item>
                    ";
        $item_str = "";
        $link=strval("http://mp.weixin.qq.com/s?__biz=MzIwOTM3Mjk4Nw==&mid=100000060&idx=1&sn=933396b0dbdf64cc2f19f51b0366f85c&scene=0&previewkey=B%2FR4rwNMvCyHLa61rUF8pswqSljwj2bfCUaCyDofEow%3D#wechat_redirect");
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, "为什么要用易卡系统？打开了解我们", "了解易卡，了解一款帮你赚钱的收银系统","http://vip.yikant.com/Public/images/0.jpg","http://955.cc/cdzW3");
        }  
        $newsTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <Content><![CDATA[]]></Content>
        <ArticleCount>%s</ArticleCount>
        <Articles>
        $item_str</Articles>
        </xml>";
        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), 1);
        return $result;
    }
    

}